/*
 * @Author: sunzhijun 
 * @Date: 2019-03-26 10:15:35 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2020-04-15 16:13:04
 */
import React, { Component, PureComponent } from 'react';
import ReactDOM from 'react-dom';
import { high, createPage, base, getUrlParam, toast, promptBox, cacheTools } from 'nc-lightapp-front';
import { hrAjax as ajax, saveValidate } from 'src/hrpub/common/utils/utils';
import handdleCheckedData from '../../../../public/functions/checkDataPermissionAction';
import Header from '../components/Header';
import Pagination from '../components/Pagination';
import NewIncreased from '../../../../public/components/NewIncreased';
import ModalFormCard from '../components/ModalFormCard';
// import NCBackBtn from "../../../../../hrpub/common/components/hr-back/index";
import EmptyData from "src/hrpub/common/components/emptyImg";
import IsMac from '../../../../public/functions/isMac';
import { chectFormAction } from '../../../../public/functions/checkFormAction';
import setAllpks from '../../../../public/functions/setAllpks';
import './index.less';
import NCUploader from 'uap/common/components/NCUploader';
import WpsModal from 'src/hrpub/common/components/wpsPreModel';
import deepCopy from '../../../../../hrpub/common/utils/deep-copy';
const { NCButton, NCSelect, NCCheckbox } = base;
const NCOption = NCSelect.NCOption;




const appcode = "60110501", pagecode = "60110501p";
let tableid = 'dataList';
let cardId = 'dataCard';

const moduleId = "sign6011";
const domainName = "hrcm";

class protocolmgtSign extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            this.registed = ['postcontCard', 'secrerycontCard', 'traincontCard', 'traincontAgreeInfo', 'traincontBusinessInfo', 'traincontTrainInfo', 'hrcm_agreement_template', 'secrerycontCard_add', 'postcontCard_add', 'traincontCard_add', 'postcontList', 'secrerycontList', 'traincontList', 'psnList'];
            props.use.form('postcontCard','secrerycontCard', 'traincontCard', 'traincontAgreeInfo', 'traincontBusinessInfo', 'traincontTrainInfo', 'hrcm_agreement1Card_add','hrcm_agreement_template', 'secrerycontCard_add', 'postcontCard_add', 'traincontCard_add')
            props.use.editTable('postcontList', 'secrerycontList', 'hrcm_agreement1List','traincontList', 'psnList')
            props.use.search('query', 'listquery')
        }
        this.formrelationArr = ['traincontAgreeInfo', 'traincontTrainInfo', 'traincontBusinessInfo'];
        this.config = {
            pagecode: pagecode,
            appcode: appcode
        };
        this.state = {
            json: {},
            showMode: 'browse',
            setModalVisible: false,
            showUploader: false, //是否显示附件管理
            isDataListPage: true, //是否是列表数据页面
            rowsListData: [],  //新增查询所选数据 
            rowsCardData: [],
            agreementType: null,  //协议类型 20190711 默认从协议类型接口中获取第一个数据
            isInterrupt: true, //阻止下一步
            pageInfo: {
                pageIndex: 1,
                pageSize: 10
            }, 
            nodeRefs:{wpsview: null}
        }
        props.createUIDom(this.config, (data) => {
            let oid = data.template.listquery.oid;
            this.setTemplateData(data);
            this.setState({
                buttons: data.button || [],
                context: data.context || {},
                telName: data.template.name || '',
                oid: oid,
                templateId: data.template.pageid
            });
            // 因为有自定义得 这里需要重新注册
            let temp = deepCopy(data.template);
            for (let key in temp) {
                if(temp.hasOwnProperty(key) && temp[key].moduletype){
                    if(!this.registed.includes(temp[key].code)) {
                        temp[key].moduletype === 'form' && props.use.form(temp[key].code);
                        temp[key].moduletype === 'table' && props.use.editTable(temp[key].code);
                        this.registed.push(temp[key].code);
                    }
            　　}
            }

            props.meta.setMeta(data && data.template ? data.template : {}, () => { });
            props.button.setButtons(data && data.button ? data.button : {});
        });
        this.prevHandleData = this.prevHandleData.bind(this);
        this.nextDetailData = this.nextDetailData.bind(this);
        this.saveTableData = this.saveTableData.bind(this);
        this.onHideUploader = this.onHideUploader.bind(this);
        this.takeEffectEvent = this.takeEffectEvent.bind(this);
        this.refreshTableData = this.refreshTableData.bind(this);
        this.closeModal = this.closeModal.bind(this);
        this.doneSetting = this.doneSetting.bind(this);
        this.childPrevHandle = this.childPrevHandle.bind(this);
        this.setRollBackFlag = this.setRollBackFlag.bind(this);
    }

    componentWillMount() {
        window.location.hash = `?page=201908221110`;
        let callback = (json, status, inlt) => {
            if (status) {
                this.lang = json
                this.setState({ json, inlt })//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({ moduleId: moduleId, domainName: domainName, callback })
    }

    componentDidMount() {
        this.getAgreementType();
        this.updateButtonStatus();
        // 计算列表的高度
        let bodyH = this.refs.getContainerDom.offsetHeight;
        let headerH = this.header.getHeaderH();
        this.setState({
            tableHeight: bodyH - headerH - 44
        })
        this.props.button.setButtonVisible(['newAdd', 'delete', 'refresh', 'takeEffect', 'edit', 'save', 'cancel', 'edit', 'text', 'file', 'query'], false);
    }

    //设置模板信息
    setTemplateData(data) {
        let listIdArr = new Set(['postcontList', 'secrerycontList', 'traincontList']);
        let template = data && data.template;
        for (let name in template) {
            if (name.indexOf('List') >= 0) {
                listIdArr.add(name)
            }
        }
        listIdArr = Array.from(listIdArr);
        listIdArr.forEach((v, i) => {
            let dataItems = data.template[v].items;
            this.initMeta(dataItems, this);
        });
    }

    //初始化模板信息
    initMeta(data, opt) {
        let { json } = this.state;
        // 添加序号列
        data.unshift({
            attrcode: 'index',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000039'], // 序号
            width: '65px',
            textAlign: 'center',
            visible: true,
            fixed: 'left',
            render(text, record, index) {
                return (
                    <span>{index + 1}</span>
                )
            }
        });
        // 添加超链接和锁定列
        data.forEach((item, key) => {  //添加超链接
            switch (item.attrcode) {
                case 'contcode':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.render = (text, record, index) => {
                        return (
                            <span className="list-style" style={{ color: '#0073E1', cursor: 'pointer' }}
                                onClick={this.toCardForm.bind(this, record, index, this.props)}>
                                {record && record.values['contcode'] && record.values['contcode'].value}
                            </span>
                        );
                    };
                    break;
                case 'pk_psndoc.code':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.render = (text, record, index) => {
                        return (
                            <span className="list-style" onClick={this.toCardForm.bind(this, record, index, this.props)}>
                                {record && record.values['pk_psndoc.code'] && record.values['pk_psndoc.code'].value}
                            </span>
                        );
                    };
                    break;
                case 'pk_psndoc.name':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.render = (text, record, index) => {
                        return (
                            <span className="list-style"  onClick={this.toCardForm.bind(this, record, index, this.props)}>
                                {record && record.values['pk_psndoc.name'] && record.values['pk_psndoc.name'].value}
                            </span>
                        );
                    };
                    break;
                default: break;
            }
        });
        //添加附件
        data.push({
            attrcode: 'attachment',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000011'], /* 国际化处理： 附件管理*/
            width: '80px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                // let billId = record.values.pk_agreement.value;
                // let billNo = record.values.contcode.value
                return (
                    <span>
                        <i className="icon iconfont icon-fujianshenpi" onClick={(eve) => opt.attachManage(record)}></i>
                    </span>
                )
            }
        });
        data.push({
            attrcode: 'handleArea',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000012'], /* 国际化处理： 操作*/
            width: '250px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                let billId = record.values.pk_agreement.value;
                let billNo = record.values.contcode.value
                return (
                    <div>
                        <span style={{ color: '#0073E1', cursor: 'pointer', marginRight: '12px' }}
                            onClick={opt.modifyCheckData.bind(opt, record)}
                        >
                            {json['hrcm-000013']}
                        </span>
                        <span style={{ color: '#0073E1', cursor: 'pointer', marginRight: '12px' }}
                            onClick={opt.deleteBatchesData.bind(opt, record)}
                        >
                            {json['hrcm-000014']}
                        </span>
                        <span style={{ color: '#0073E1', cursor: 'pointer' }}
                            onClick={opt.contractText.bind(opt, billId, record)}
                        >
                            {json['hrcm-000032']}
                        </span>
                    </div>
                )
            }
        });
    }

    //根据获取本地存储的主键信息获取数据
    getStorageData() {
        let storage = JSON.parse(window.localStorage.getItem('pageQueryParam'));
        let storageData = storage && Object.keys(storage);
        if (storageData && !!storageData.length) {
            let storage_pk = storage && storage.signPro && storage.signPro.pk_psndoc_subs;
            let hrorgobj = storage && storage.signPro && storage.signPro.hrorgobj;
            this.header.setOrganizationValue(hrorgobj);
            hrorgobj && this.setState({
                pk_org: hrorgobj.refpk
            }, () => {
                this.fetchTableData()
            })
        }
    }


    //查询设置组织pkorg
    searchOrganizationChange(data) {
        let pkorg = data.refpk;
        this.setState({
            pk_org: pkorg
        }, () => {
            this.fetchTableData();
        })
    }

    //选择协议类型
    selectAgreementType(type) {
        this.setState({
            agreementType: type,
        }, () => {
            this.fetchTableData();
            this.setFormrelation();
        })
    }

    //格式化协议主键
    formatPkGgreement(key, pageId) {
        if (key && key.jobpks) {
            if (pageId != tableid) {
                let len = key.jobpks.length;
                key = key.jobpks[len - 1];
            } else {
                key = [];
            }
        }
        if (typeof (key) == 'string') {
            key = [key];
        } else {
            key = [];
        }
        return key;
    }

    //数据初始化
    fetchTableData(key, flag, conditions) {
        let { isDataListPage, pk_org, agreementType, json, pageInfo } = this.state;
        let pageType = isDataListPage ? tableid : cardId;
        let pageId = this.updateTemplateId();
        let pkGgreement = this.formatPkGgreement(key, pageId);
        if (!!pk_org) {
            ajax({
                url: '/nccloud/hrcm/agreement/SignQueryAction.do',
                data: {
                    pk_org: pk_org,
                    agreementType: agreementType,
                    areaCode: pageId,
                    pageType: pageType,
                    pkGgreement: pkGgreement,
                    pageInfo: pageInfo,
                    appCode: '60110501',
                    ...conditions
                },
                success: res => {
                    if (res.success && res.data) {
                        let data = res.data;
                        let rowsData,allpks;
                        if (this.state.isDataListPage) {
                            allpks = data[pageId].allpks || [];
                            rowsData = data && data[pageId].rows;
                            this.setListButtonStatus();
                            this.props.button.setButtonDisabled(['newAdd', 'edit', 'delete', 'text', 'refresh', 'takeEffect', 'file', 'query'], false);
                            this.props.editTable.setTableData(pageId, { rows: rowsData || [] });
                            //设置翻页数据
                            this.setState({
                                pageInfo: res.data[pageId].pageInfo,
                                isVisiblePagination: true   //控制翻页显示隐藏
                            })
                            cacheTools.set('allpks', allpks);
                        } else {
                            rowsData = res.data && res.data[pageId].rows[0];
                            if (!!rowsData.values.ifprop) {
                                !!rowsData.values.ifprop.value ? rowsData.values.ifprop.display = json['hrcm-000018'] : rowsData.values.ifprop.display = json['hrcm-000019']
                            }
                            if (!!rowsData) {
                                let formData = {
                                    rows: new Array(rowsData)
                                };
                                this.props.form.setAllFormValue({ [pageId]: formData });
                            }
                            if (!!key.jobpks || Array.isArray(key)) { //数组是新增过来的数据
                                allpks = cacheTools.get('allpks');
                                if(!!key.jobpks){
                                    key = key.jobpks;
                                }
                                let newAllpks = allpks.concat(key);
                                let len = key.length;
                                newAllpks = Array.from(new Set(newAllpks));
                                cacheTools.set('allpks', newAllpks);
                                this.header.setCardPagination(key[len - 1]);
                            }else if(!!key){      //字符串是删除生效时的数据
                                this.header.setCardPagination(key);
                            }
                            this.hidePagination();
                        }
                    } else {
                        this.props.button.setButtonVisible({
                            newAdd: true,
                            delete: true,
                            refresh: true,
                            takeEffect: true,
                            save: false,
                            cancel: false,
                            file: false,
                            query: true
                        })
                        this.props.button.setButtonDisabled({
                            edit: true,
                            delete: true,
                            text: true,
                            takeEffect: true,
                            newAdd: false
                        })
                        this.props.editTable.setTableData(pageId, { rows: [] });
                        this.props.form.EmptyAllFormValue(pageId);
                        this.hidePagination();
                    }
                    if (!!flag) {
                        toast({ color: 'success', content: json['hrcm-000016'] });
                    }
                    this.deleteStorage();
                    // window.localStorage.removeItem('pageQueryParam');
                },
                error: err => {
                    this.props.button.setButtonVisible(['save', 'cancel', 'file'], false);
                    this.props.button.setButtonDisabled(['edit', 'delete', 'text', 'takeEffect'], true);
                    this.props.button.setButtonDisabled(['newAdd'], false);
                    this.props.editTable.setTableData(pageId, { rows: [] });
                    this.hidePagination();
                    // toast({color: 'danger', content: err.message});
                }
            })
        } else {
            this.props.button.setButtonVisible(['newAdd', 'edit', 'delete', 'text', 'takeEffect', 'refresh', 'query'], false);
            this.hidePagination();
        }
    }

    //删除localStorage
    deleteStorage(){
        let pageQueryParamObj = JSON.parse(localStorage.getItem('pageQueryParam'));
        if(!!pageQueryParamObj){
            delete pageQueryParamObj.signPro;
            localStorage.setItem('pageQueryParam',JSON.stringify(pageQueryParamObj));
        }
    }


    //获取协议类型
    getAgreementType() {
        ajax({
            url: '/nccloud/hrcm/agreement/AgreementTypeQueryAction.do',
            data: {
                appCode: appcode
            },
            success: res => {
                if (res.success && res.data) {
                    this.setState({
                        agremeentTypeData: res.data,
                        agreementType: res.data[0].code
                    },()=>{
                        this.getStorageData();
                    })

                }
            }
        })

    }

    //隐藏列表翻页
    hidePagination() {
        this.setState({
            isVisiblePagination: false   //控制翻页显示隐藏
        })
    }

    //列表页面
    getTableListData() {
        let { pk_org, json } = this.state;
        let tableHeight = this.state.tableHeight;
        if (!!pk_org) {
            return (
                <div className="nc-singleTable-table-area nc-bill-table-area">
                    {this.props.editTable.createEditTable(this.state.pageId, {
                        //showIndex: true, 		//显示序列号
                        showCheck: true,        //显示复选框
                        cancelCustomRightMenu: true,
                        onRowDoubleClick: this.toCardForm.bind(this),    //编辑表格数据
                        sort: { mode: 'single', backSource: false, sortFun: (v, rows) => { setAllpks(rows, 'pk_agreement') } },
                        // onSelected: this.getSelectedData.bind(this),     //获取选中的数据
                        height: tableHeight - 72    //设置高度
                    })}
                </div>
            )
        } else {
            return (
                <EmptyData text={json['hrcm-000017']}></EmptyData>
            )
        }
    }

    //卡片编辑后事件
    handleEditFormDate(props, moduleId, key, value) {
        let { pageId } = this.state;
        chectFormAction(key, moduleId, props, [pageId]);
    }

    //编辑FormCard前方法
    handleEditBefore(props, moduleId, key, value,data) {
        let { agreementType, pk_org } = this.state;
        if (key == 'pk_conttext') {
            let meta = this.props.meta.getMeta();
            let obj = {
                "pk_org": pk_org,
                "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder",
                "agreementType": agreementType
            }
            this.setQueryCondition(moduleId, key, obj);
        }else if(key  === 'pk_post'){
            let pk_dept = data['pk_psnjob.pk_dept.pk_dept'] && data['pk_psnjob.pk_dept.pk_dept'].value;
            let obj = {
                "pk_dept": pk_dept
            }
            this.setQueryCondition(moduleId, key, obj);
        }
        return true;
    }

    // 编辑前事件操作增加queryCondition条件
    setQueryCondition(moduleId, key, param){
        let meta = this.props.meta.getMeta();
        if(!!meta[moduleId].items.find(item => item.attrcode === key)){
            meta[moduleId].items.find(item => item.attrcode === key).queryCondition = function () {
                return param
            };
        }else{
            meta['traincontAgreeInfo'].items.find(item => item.attrcode === key).queryCondition = function () {
                return param
            };
        }
        this.props.meta.setMeta(meta);
    }

    //表单卡片页面
    showFormCardData(pageId) {
        return (
            <div className="header-cardPagination-area">
                {this.props.form.createForm(pageId, {
                    useFixedHeader: true,
                    onAfterEvent: this.handleEditFormDate.bind(this),
                    onBeforeEvent: this.handleEditBefore.bind(this),
                    expandArr: this.formrelationArr // 设置关联表单某个区域展开
                })}
            </div>
        )
    }

    //修改保存
    saveTableData(step) {
        let { json, agreementType, templateId, pageId } = this.state;
        let selectFormData = this.props.form.getAllFormValue(pageId).rows;
        let stepNum = step ? step : '0';
        let bodys_code = null;
        let billType = 'form';
        let formData = {
            model: {
                rows: selectFormData
            }
        }
        if(agreementType === 'traincont'){
            bodys_code = this.formrelationArr;
            billType = 'extcard';
        }
        saveValidate(this.props, templateId, pageId, bodys_code, billType).then(()=>{
            if (this.props.form.isCheckNow(pageId)) {
                ajax({
                    url: '/nccloud/hrcm/agreement/SignUpdateSaveAction.do',
                    data: {
                        step: stepNum,
                        formData: formData,
                        agreementType: agreementType
                    },
                    success: res => {
                        if (res.success && res.data) {
                            let data = res.data;
                            let fn = {
                                sureFn: this.isTakeEffectEvent.bind(this)
                            }
                            let content = {
                                content: data.msg
                            }
                            if (data.step == '1') {
                                content.sureName = json['hrcm-000034'];
                                content.cancelName = json['hrcm-000035'];
                                this.refreshTableData();
                                this.updateShowMode('browse');
                                this.promptBoxModal(content, fn, '1');
                            } else {
                                this.refreshTableData();
                            }
                        }
                    }
                })
            }
        });
    }

    //操作卡片翻页
    handleCardPagination(pks) {
        this.fetchTableData(pks);
    }

    //确认弹窗
    promptBoxModal(context, fn = {}, args) { //context 内容；fn 执行的方法；args 传递的参数
        let { sureFn, cancelFn } = fn;
        let { json } = this.state;
        promptBox({
            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: json['hihr-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
            content: context.content,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
            beSureBtnName: context.sureName ? context.sureName : json['hihr-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
            cancelBtnName: context.cancelName ? context.cancelName : json['hihr-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
            hasCloseBtn: true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
            // beSureBtnClick: ()=>{ this.resetTableData() },   // 确定按钮点击调用函数,非必输
            beSureBtnClick: () => { sureFn && sureFn(args) },   // 确定按钮点击调用函数,非必输
            cancelBtnClick: () => { cancelFn && cancelFn(args) },  // 取消按钮点击调用函数,非必输
            // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
            closeByClickBackDrop: false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
        })
    }
    //刷新
    refreshTableData(flag) {
        this.setState({
            isDataListPage: !this.state.isDataListPage ? false : true
        }, () => {
            if (this.state.isDataListPage) {
                this.fetchTableData('', flag);
            } else {
                let key = this.props.form.getAllFormValue(this.state.pageId).rows[0].values.pk_agreement.value;
                this.fetchTableData(key, flag);
            }
        })

    }

    //获取某一处修改的数据索引
    searchIndex(arr, id) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].rowid == id) {
                return i;
            }
        }
    }

    // 按钮是否显示，按钮是否可用
    updateButtonStatus() {
        var showMode = this.state.showMode
        this.props.button.setButtonsVisible({
            newAdd: showMode === 'browse',
            edit: showMode === 'browse',
            delete: showMode === 'browse',
            text: showMode === 'browse',
            refresh: showMode === 'browse',
            takeEffect: showMode === 'browse',
            file: showMode === 'browse',
            save: showMode === 'edit',
            cancel: showMode === 'edit'
        })
    }

    // 更新界面状态
    updateShowMode(showMode) {
        // var oldMode = this.state.showMode;
        let { pageId, json } = this.state;
        this.setState({
            showMode: showMode
        }, () => {
            this.updateButtonStatus()
        })
        // if(oldMode === showMode) {
        //     return;
        // }
        if ('edit' === showMode) {
            this.props.form.setFormStatus(pageId, 'edit');
            // this.props.editTable.setStatus(tableid,'edit');
            // this.props.editTable.setColEditableByKey(tableid, "table",false)
        } else {
            // this.props.editTable.cancelEdit(tableid);
            this.props.form.cancel(pageId);
            // this.props.form.setFormStatus(pageId,'browse');
            this.header.setCardPaginationVisibleFn(true);
            let formData = this.props.form.getAllFormValue(pageId);
            if(formData && formData.rows[0].values.ifprop){
                if (formData.rows[0].values.ifprop.value === 'Y' || formData.rows[0].values.ifprop.value === true) {
                    this.props.form.setFormItemsValue(pageId, { 'ifprop': { display: json['hrcm-000018'], value: "Y", scale: "-1" } })
                } else {
                    this.props.form.setFormItemsValue(pageId, { 'ifprop': { display: json['hrcm-000019'], value: "N", scale: "-1" } })
                }
            }
        }
    }

    //设置setRollBackFlag
    setRollBackFlag(rollBackFlag, agreementType){
        this.setState({
            rollBackFlag: rollBackFlag,
            agreementType: agreementType
        })
    }

    //取消下一步人员数据被占用
    cancelOccupy() {
        let { rollBackFlag, pk_org, agreementType} = this.state;
        let formCardId = this.formCard.getFormCardId();
        if (!!formCardId) {
            let occupyData = this.props.form.getAllFormValue(formCardId);
            let occupyCode = occupyData && occupyData.rows[0].values.contcode.value;
            if (rollBackFlag && !!occupyCode) {
                let occupyCodeArr = new Array(occupyCode);
                ajax({
                    url: '/nccloud/hrcm/common/CodeRollBackAction.do',
                    data: {
                        codeList: occupyCodeArr,
                        pk_org: pk_org,
                        agreement_type: agreementType
                    },
                    success: res => {
                        if (res.success) {
    
                        }
                    }
                })
            }
        }
    }

    //关闭modal弹窗
    closeModal(jobpks, agFlag) {
        if (!!agFlag) { //已选择协议
            this.setState({
                setModalVisible: false
            }, () => {
                if (agFlag) {
                    this.setState({
                        setModalVisible: true,
                        agFlag: agFlag
                    }, () => {
                        this.newIncreased.getSearchData([], jobpks);
                    })
                }
                this.fetchTableData();
            });
        } else {
            this.cancelOccupy();
            this.setState({
                setModalVisible: false,
                agFlag: false
            }, () => {
                if (!!jobpks) {
                    this.fetchTableData({ jobpks });
                }
            });
        }
    }

    //上一步
    prevHandleData() {
        this.cancelOccupy();
    }

    //子组件调用父组件上一步操作
    childPrevHandle() {
        this.newIncreased.prevHandleFn();
    }

    //下一步
    nextDetailData(selectData, agreementType) {
        let pk_psnjob = [];
        selectData && selectData.map((v,i)=>{
            pk_psnjob.push(v.data.values.pk_psnjob.value);
        });
        // window.localStorage.setItem("listData", JSON.stringify(pk_psnjob));
        this.setState({
            rowsListData: pk_psnjob
        },()=>{
            this.formCard.getFormCardData(selectData, agreementType);
        })
    }

    //点击完成保存
    doneSetting(agFlag, agreementType) {
        //调用协议保存
        // let listDataStorage = JSON.parse(window.localStorage.getItem('listData'));
        let { rowsListData } = this.state;
        this.formCard.doneAgreementData(agreementType, rowsListData);
    }

    //列表页按钮状态
    setListButtonStatus() {
        this.props.button.setButtonVisible({
            newAdd: true,
            delete: true,
            refresh: true,
            takeEffect: true,
            query: true,
            save: false,
            cancel: false,
            text: false,
            edit: false,
            file: false
        });
    }

    //返回
    handleBackClick() {
        this.setState({
            isDataListPage: true
        }, () => {
            this.setListButtonStatus();
            this.fetchTableData();
        })
    }

    //获取选中的数据
    // getSelectedData(a,b,c){
    //     console.log("cccc",c);
    //     let oldDefaultData = defaultRowsData;
    //     if(c && c.selected){
    //         defaultRowsData = c;
    //     }else{
    //         defaultRowsData = oldDefaultData;
    //     }
    // }

    //更新模板id
    updateTemplateId() {
        let { agreementType, isDataListPage } = this.state;
        let pageId = isDataListPage ? agreementType + 'List' : agreementType + 'Card';
        // 设置模板Id
        this.setState({
            pageId: pageId
        })
        return pageId;
    }

    //进入CardForm
    toCardForm(records) {
        let { agreementType } = this.state;
        this.setState({
            isDataListPage: false,
            isVisiblePagination: false, //控制翻页显示隐藏
            pageId: agreementType + 'Card'
        }, () => {
            // let id = this.updateTemplateId();
            let pk_agreement = records.values.pk_agreement.value;
            let { pageId } = this.state;
            this.editTableFn(records, pageId);
            this.header.showHeadLeftFn(true, pk_agreement);
            this.header.getCardFormId(pageId);
        })
    }

    //设置formrelation
    setFormrelation() {
        let { agreementType } = this.state;
        if (agreementType == 'traincont') {
            let template = {
                formrelation: {
                    traincontCard: this.formrelationArr
                }
            }
            this.props.meta.addMeta(template);
        } else {
            let getMeta = this.props.meta.getMeta().formrelation;
            let getFormrelation = getMeta && getMeta.formrelation;
            if (!!getFormrelation) {
                delete getFormrelation.traincontCard;
                template.formrelation = getFormrelation;
                this.props.meta.addMeta(template);
            }
        }
    }
    //进入CardForm展示数据
    editTableFn(records, id) {
        let { pageId, json } = this.state;
        let rowsData;
        if (records) {
            rowsData = records;
        } else {
            rowsData = this.props.editTable.getCheckedRows(pageId)[0].data;
        }
        let formData = {
            rows: new Array(rowsData)
        };
        this.props.form.setAllFormValue({ [pageId]: formData });
        this.props.button.setButtonVisible(['file', 'edit', 'text'], true);
        this.props.button.setButtonVisible(['query'], false);
        if(formData && formData.rows[0].values.ifprop){
            if (formData.rows[0].values.ifprop.value === true || formData.rows[0].values.ifprop.value === 'Y' ) {
                this.props.form.setFormItemsValue(pageId, { 'ifprop': { display: json['hrcm-000018'], value: "Y", scale: "-1" } })
            } else {
                this.props.form.setFormItemsValue(pageId, { 'ifprop': { display: json['hrcm-000019'], value: "N", scale: "-1" } })
            }
        }
        // chectFormAction('termtype', pageId, this.props, [pageId]);
    }

    // 修改数据校验事件
    modifyCheckData(v){
        let { isDataListPage, pageId } = this.state;
        let pk_agreement,formCardData;
        if( isDataListPage ){
            pk_agreement = v.values.pk_agreement.value;
        }else{
            formCardData = this.props.form.getAllFormValue(pageId);
            pk_agreement = formCardData && formCardData.rows[0].values.pk_agreement.value;
        }
        handdleCheckedData(pk_agreement, 'edit', 'agreement', ()=>{
            if( isDataListPage ){
                this.modifyListData(v);
            }else{
                this.editCardData(formCardData);
            }
        });
    }

    //修改列表数据
    modifyListData(v) {
        let formData = v;
        let { agreementType } = this.state;
        this.setState({
            isDataListPage: false,
            isVisiblePagination: false,
            pageId: agreementType + 'Card'
        }, () => {
            let { pageId } = this.state;
            formData = {
                rows: new Array(formData)
            };
            // this.updateTemplateId();
            this.header.showHeadLeftFn(true);
            this.props.form.setAllFormValue({ [pageId]: formData });
            this.editCardData(formData);
        });
        // this.props.editTable.getCheckedRows(this.state.pageId);
    }

    //编辑卡片时数据
    editCardData(formData) {
        let { pageId, json, agreementType, pk_org } = this.state;
        let extendParam = {
            pk_org: pk_org
        }
        this.props.form.setFormItemAutoFocus(pageId, 'contcode');
        this.props.form.setFormStatus(pageId, 'edit');
        this.header.setCardPaginationVisibleFn(false);
        this.header.getCardFormId(pageId);
        this.props.button.setButtonVisible(['newAdd', 'edit', 'delete', 'text', 'refresh', 'takeEffect', 'file', 'query'], false);
        this.props.button.setButtonVisible(['save', 'cancel'], true);
        chectFormAction('', pageId, this.props, [pageId], appcode, extendParam);
        if(formData && formData.rows[0].values.ifprop){
            if (formData.rows[0].values.ifprop.value === 'Y' || formData.rows[0].values.ifprop.value === true) {
                this.props.form.setFormItemsValue(pageId, { 'ifprop': { display: json['hrcm-000018'], value: "Y", scale: "-1" } })
            } else {
                this.props.form.setFormItemsValue(pageId, { 'ifprop': { display: json['hrcm-000019'], value: "N", scale: "-1" } })
                this.props.form.setFormItemsDisabled(pageId, { 'promonth': true, 'prop_unit': true, 'probegindate': true, 'probenddate': true });
            }
        }
    }
    // 点击生效事件
    isTakeEffectEvent(step){
        let pks = this.getPkPsndocSub();
        !!pks && handdleCheckedData(pks, 'effect', 'agreement', ()=>{
            this.takeEffectEvent(step);
        });
    }
    //是否生效
    takeEffectEvent(step, info) {
        // let pageType = '';
        let { isDataListPage, json } = this.state;
        let formData = [];
        let stepNum = step ? step : '0';
        let isCard = isDataListPage ? false : true;
        let selectCtrtpks = [];

        if (!isCard) {
            // pageType = 'list';
            let checkedData = this.props.editTable.getCheckedRows(this.state.pageId);
            if (!checkedData.length) {
                toast({ color: 'warning', content: json['hrcm-000020'] });
                return;
            }
            checkedData.map((v) => {
                selectCtrtpks.push(v.data.values.pk_agreement.value);
            })
        } else {
            // pageType = 'card';
            selectCtrtpks.push(this.props.form.getAllFormValue(this.state.pageId).rows[0].values.pk_agreement.value);
        }
        ajax({
            url: '/nccloud/hrcm/agreement/SignMakeEffectiveAction.do',
            data: {
                step: stepNum,
                selectCtrtpks: selectCtrtpks
            },
            success: res => {
                if (res.success && res.data) {
                    let data = res.data;
                    let info = res.data.info || null;
                    if (data.step == '99') {
                        if (isCard) {
                            let allpks = cacheTools.get('allpks') || [];
                            let index = 0;
                            let len = allpks.length;
                            len && allpks.forEach((v, i) => {
                                if (v == selectCtrtpks) {
                                    allpks.splice(i, 1);
                                    if (i < len - 1) {
                                        index = i;
                                    } else if (i == len - 1) {
                                        index = i - 1;
                                    }
                                }
                            })
                            cacheTools.set('allpks', allpks);
                            this.fetchTableData(allpks[index]);
                        } else {
                            this.fetchTableData();
                        }
                    } else {
                        let fn = {
                            sureFn: this.takeEffectEvent
                        }
                        let content = {
                            content: data.msg,
                            sureName: json['hrcm-000034'],
                            cancelName: json['hrcm-000035']
                        }
                        this.promptBoxModal(content, fn, data.step, info);
                    }
                }
            }
        })
    }

    // 关闭附件
    onHideUploader() {
        this.setState({
            showUploader: false
        })
    };

    //批量删除
    deleteBatchesData(v) {
        let pks;
        if( !!v ){
            pks = v && v.values.pk_agreement.value;
        }else{
            pks = this.getPkPsndocSub();
        }
        !!pks && handdleCheckedData(pks, 'delete', 'agreement', ()=>{
            this.delPrompt(pks)
        });
    }

    // 删除确认弹窗
    delPrompt(delDataPks){
        let { json } = this.state;
        let fn = {
            sureFn: () => { this.deleteData(delDataPks) }
        }
        let content = {
            content: json['hrcm-000021']
        }
        this.promptBoxModal(content, fn);
    }

    //获取主键
    getPkPsndocSub(){
        let { isDataListPage, json, pageId } = this.state;
        let isCard = isDataListPage ? false : true;
        let pks=[];
        if(isCard){
            pks = this.props.form.getAllFormValue(pageId).rows[0].values.pk_agreement.value;
        }else{
            let checkedData = this.props.editTable.getCheckedRows(pageId);
            if(!checkedData.length){
                toast({color: 'warning', content: json['hrcm-000020']});
                return;
            }
            checkedData.map((v)=>{
                pks.push(v.data.values.pk_agreement.value);
            })
        }
        return pks;
    }

    //是否删除行上数据
    // isDeleteRowData(v) {
    //     let { json } = this.state;
    //     let fn = {
    //         sureFn: this.deleteRowData.bind(this)
    //     }
    //     let content = {
    //         content: json['hrcm-000021']
    //     }
    //     this.promptBoxModal(content, fn, v);
    // }

    // deleteRowData(v) {
    //     let PKsData = v.values.pk_agreement.value;
    //     this.deleteData(PKsData);
    // }

    //删除数据
    deleteData(PKsData) {
        let isCard = this.state.isDataListPage ? false : true;
        ajax({
            url: '/nccloud/hrcm/agreement/SignDeleteAction.do',
            data: {
                // pk_org: this.state.pk_org,
                agreementType: this.state.agreementType,
                selectCtrtpks: PKsData
            },
            success: res => {
                if (res.success && res.data) {
                    if (isCard) {
                        let allpks = cacheTools.get('allpks') || [];
                        let index = 0;
                        let len = allpks.length;
                        len && allpks.forEach((v, i) => {
                            if (v == PKsData) {
                                allpks.splice(i, 1);
                                if (i < len - 1) {
                                    index = i;
                                } else if (i == len - 1) {
                                    index = i - 1;
                                }
                            }
                        })
                        cacheTools.set('allpks', allpks);
                        if(allpks.length === 0){
                            this.header.handleBackBtn()
                        }else{
                            this.fetchTableData(allpks[index]);
                        }
                    } else {
                        this.fetchTableData();
                    }
                }
            }
        })
    }

    //合同文本
    contractText(v, data) {
        let pks = v;
        let json = this.state.json;
        if (IsMac(json['hrcm-000040'])) {
            return false
        }
        ajax({
            url: '/nccloud/hrcm/templet/AgreementTextViewAction.do',
            data: {
                pk_org: this.state.pk_org,
                pk_agreement: pks,
            },
            success: res => {
                if (res.success && !!res.data) {
                    if (this.state.isDataListPage) {
                        this.state.nodeRefs.wpsview.openView([{data: data}], 'ag')
                    } else {
                        this.state.nodeRefs.wpsview.openView(data.rows, 'ag')
                    }
                    // let protocol = window.location.protocol;
                    // let host = window.location.host;
                    // let openUrl = "uclient://start/" + protocol + "//" + host + res.data;
                    // // window.open(openUrl, '_self');
                    // top.location.href = openUrl;
                } else {
                    toast({ color: 'warning', content: res.error.message });
                }
            }
        })
    }

    //操作翻页方法
    changePagination(pageInfo) {
        this.setState({
            pageInfo
        }, () => {
            // this.fetchTableData();
            let getConditions = this.props.search.getQueryInfo('listquery',true);
            let conditions = getConditions;
            this.fetchTableData( '','',conditions);
        })
    }

    //改变每页展示数据量
    pageSizeSelect(pageInfo) {
        this.setState({
            pageInfo
        }, () => {
            // this.fetchTableData();
            let getConditions = this.props.search.getQueryInfo('listquery',true);
            let conditions = getConditions;
            this.fetchTableData( '','',conditions);
        })
    }

    //取消编辑态
    cancelEditStatus() {
        let { json } = this.state;
        let fn1 = {
            sureFn: this.updateShowMode.bind(this)
        }
        let content = {
            content: json['hrcm-000022']
        }
        this.promptBoxModal(content, fn1, 'browse');
    }

    //附件管理
    attachManage(record) {
        let { pageId } = this.state;
        let billId,billNo;
        if(!!record){
            billId = record.values.pk_agreement.value;
            billNo = record.values.contcode.value
        }else{
            let cardData = this.props.form.getAllFormValue(pageId).rows[0].values;
            billId = cardData.pk_agreement.value;
            billNo = cardData.contcode.value;
        }

        handdleCheckedData(billId, 'attachment', 'agreement', ()=>{
            this.setState({
                showUploader: true,
                billId: billId,
                billNo: billNo
            })
        });
    }

    //打开查询
    listQuery () {
        let { pk_org } = this.state;
        this.props.search.openAdvSearch('listquery', true, ()=>{
            let meta = this.props.meta.getMeta();
            let items = meta.listquery.items;
            items.length > 0 && items.map((item,index)=>{
                if(item.attrcode === 'pk_psnjob.pk_dept'){
                    item.queryCondition = {
                        pk_hrorg: pk_org
                    }
                }
            })
            this.props.meta.setMeta(meta);
        });
    }
    // 查询数据
    searchData = () => {
        // let conditions = props.search.getAllSearchData('query').conditions || [];
        let getConditions = this.props.search.getQueryInfo('listquery',true);
        let conditions = getConditions;
        this.fetchTableData( '','',conditions);
    }

    // 统一处理按钮事件
    onBtnOperation(props, btncode) {
        let { pageId, agreementType } = this.state;
        switch (btncode) {
            case 'newAdd':
                this.setState({
                    setModalVisible: true
                }, () => {
                    this.newIncreased.setAgreementType(agreementType);
                })
                break;
            case 'edit':
                // let formCardData = this.props.form.getAllFormValue(pageId);
                // this.editCardData(formCardData);
                this.modifyCheckData();
                break;
            case 'delete':
                this.deleteBatchesData();
                break;
            case 'text':
                let cardData = this.props.form.getAllFormValue(pageId);
                let pk_agreement = cardData.rows[0].values.pk_agreement.value;
                this.contractText(pk_agreement, cardData);
                break;
            case 'refresh':
                this.refreshTableData(true);
                break;
            case 'save':
                this.saveTableData();
                break;
            case 'cancel':
                this.cancelEditStatus();
                break;
            case 'takeEffect':
                this.isTakeEffectEvent();
                break;
            case 'file':
                this.attachManage();
                break;
            case 'query': 
                this.listQuery();
                break;
            default:
                break;

        }

    }
    render() {
        let { button, editTable, cardPagination, search, form } = this.props;
        const { createCardPagination } = cardPagination;
        let { createButtonApp } = button;
        let { createEditTable } = editTable;
        let { NCCreateSearch } = search;
        let { createForm } = form;
        let { pageInfo, pageId, isVisiblePagination, setModalVisible, isDataListPage, rowData, pk_org, showUploader, billId, billNo, json, isInterrupt, agremeentTypeData, oid ,agreementType, nodeRefs} = this.state;
        let modalConfig = {
            setModalVisible: setModalVisible,//是否显示新增组件
            pkOrg: pk_org,//组织编码必传
            agFlag: true//是否选中协议
        }
        return (
            <div className="nc-single-table nc-bill-card" ref="getContainerDom">
                <Header
                    {...this.props}
                    ref={node => {
                        this.header = node
                    }}
                    json={json}
                    agreementType={agreementType}
                    agremeentTypeData={agremeentTypeData}
                    appCode={appcode}
                    onBtnOperation={this.onBtnOperation.bind(this)}
                    handleBackClick={this.handleBackClick.bind(this)}
                    searchOrganizationChange={this.searchOrganizationChange.bind(this)}
                    handleCardPagination={this.handleCardPagination.bind(this)}
                    selectAgreementType={this.selectAgreementType.bind(this)}
                    cancelEditStatus={this.cancelEditStatus.bind(this)}
                >
                </Header>
                <div className="content">
                    {/* 生成表格 */}
                    {isDataListPage ? this.getTableListData() : this.showFormCardData(pageId)}
                    {/* 操作翻页 */}
                    <Pagination
                        {...this.props}
                        pageInfo={pageInfo}
                        isVisiblePagination={isVisiblePagination}
                        changePagination={this.changePagination.bind(this)}
                        pageSizeSelect={this.pageSizeSelect.bind(this)}
                    />
                </div>
                <div style={{display: "none"}}>
                    {
                        NCCreateSearch('listquery', {
                            clickSearchBtn: ()=>{ this.searchData() },
                            onlyShowAdvArea: false,
                            showAdvSearchPlanBtn: true,
                            saveSearchPlan: true,
                            oid: oid,
                            onlyShowSuperBtn: true
                        })
                    }
                </div>
                {/* 调用新增组件 */}
                {
                    setModalVisible ? <NewIncreased
                        {...this.props}
                        {...modalConfig}
                        ref={node => {
                            this.newIncreased = node
                        }}
                        // isInterrupt={isInterrupt}
                        onClose={this.closeModal}         //关闭弹窗回调
                        prevHandle={this.prevHandleData}    //上一步操作方法
                        nextHandle={this.nextDetailData}    //下一步操作方法
                        doneHandle={this.doneSetting}    //完成操作方法
                    >
                        {/* 自定义区域 */}
                        <ModalFormCard
                            {...this.props}
                            {...modalConfig}
                            ref={node => {
                                this.formCard = node
                            }}
                            prevHandleData={this.prevHandleData}
                            childPrevHandle={this.childPrevHandle}
                            closeModal={this.closeModal.bind(this)}
                            setRollBackFlag = { this.setRollBackFlag }
                            registed = {this.registed}
                        ></ModalFormCard>
                    </NewIncreased> : ''
                }
                {/* 附件管理 */}
                {showUploader && <NCUploader
                    uploadTitle={this.state.json["cm6011-000062"] /*多语: 附件管理*/}
                    billId={billId}
                    billNo={billNo}
                    placement={'top'}
                    // getGroupList = {this.getGroupList}
                    onHide={this.onHideUploader} // 关闭功能
                // beforeUpload={this.beforeUpload} 
                />
                }
                 <WpsModal
                    {...this.props}
                    onRef ={ref => nodeRefs.wpsview = ref}
                    appcode={appcode}
                    pk_org={{refpk: this.state.pk_org}}
                   />
            </div>
        );
    }
}

export default protocolmgtSign;
